import { useLocation, useNavigate } from 'react-router-dom'
import './index.less'
import { Breadcrumb } from 'antd'
import { useEffect, useState } from 'react'
import { useAppSelector } from '@/store/hooks'
const deepFilterChild = (treeData: IRoutesType[], pathname: string): IRoutesType[] => {
  return treeData?.reduce((acc: IRoutesType[], item) => {
    if (
      pathname.indexOf('/detail') > -1 &&
      item?.fullPath?.replace('/list', '/detail') === pathname &&
      acc?.filter((it) => it?.fullPath?.replace('/list', '/detail') === pathname)?.length === 0
    ) {
      acc.push(item)
    }
    if (
      pathname.indexOf('/edit') > -1 &&
      item?.fullPath?.replace('/list', '/edit') === pathname &&
      acc?.filter((it) => it?.fullPath?.replace('/list', '/edit') === pathname)?.length === 0
    ) {
      acc.push(item)
    }
    if (
      pathname.indexOf('/add') > -1 &&
      item?.fullPath?.replace('/list', '/add') === pathname &&
      acc?.filter((it) => it?.fullPath?.replace('/list', '/add') === pathname)?.length === 0
    ) {
      acc.push(item)
    }
    if (item.fullPath === pathname) {
      acc.push(item)
    }
    if (item.children && item.children.length > 0) {
      const filteredChildren = deepFilterChild(item.children, pathname)
      if (filteredChildren.length > 0) {
        const itemWithFilteredChildren = { ...item, children: filteredChildren }
        acc.push(itemWithFilteredChildren)
      }
    }
    return acc
  }, [])
}
const handleChildren = (data: IRoutesType[], arr: IRoutesType[] = []): IRoutesType[] => {
  data.forEach((item) => {
    arr.push(item)
    if (item.children && item.children.length > 0) {
      return handleChildren(item.children, arr)
    }
  })
  return arr
}
const BreadCrumb = () => {
  const navigate = useNavigate()
  const [routesInfo, setRoutesInfo] = useState<IRoutesType[]>([])
  const pathname = useLocation().pathname
  const routers = useAppSelector((state) => state.login.routeList)
  useEffect(() => {
    const result = deepFilterChild(routers, pathname)
    const routesInfo = handleChildren(result)
    setRoutesInfo(routesInfo)
  }, [pathname])
  const getItems = () => {
    return routesInfo?.map((item: any, index: number) => {
      return {
        title: (
          <span
            className={'bread_crumb_base_text ' + (index > 0 ? 'bread_crumb_base_text_bold' : '')}
            onClick={() => {
              if (index > 0) {
                if (index === routesInfo.length - 1) {
                  window.location.reload()
                } else {
                  navigate(item.fullPath)
                }
              }
            }}
          >
            {item?.name}
          </span>
        ),
        key: item?.fullPath,
      }
    })
  }
  return (
    <div className="base_layout_breadcrumb">
      <Breadcrumb items={getItems()}></Breadcrumb>
    </div>
  )
}

export default BreadCrumb
